import 'package:flutter_hcc/http/core/hi_error.dart';
import 'package:flutter_hcc/http/core/hi_net_adapter.dart';
import 'package:flutter_hcc/http/request/base_request.dart';

import 'mock_adapter.dart';

class HiNet {
  HiNet._();

  static HiNet _instance;

  static HiNet getInstance() {
    if (_instance == null) {
      _instance = HiNet._();
    }
    return _instance;
  }

  Future fire(BaseRequest request) async {
    HiNetResponse response;
    var error;

    // 打印请求信息
    printLog("request url: " + request.url());
    printLog("request headers: " + request.header.toString());
    printLog("request params: " + request.params.toString());

    try {
      response = await send(request);
    } on HiNetError catch (e) {
      error = e;
      response = e.data;
      printLog(e.message);
    } catch (e) {
      //其他异常
      error = e;
      printLog(e);
    }

    if (response == null) {
      printLog(error);
    }

    var result = response.data;
    printLog(result);
    var statue = response.statusCode;
    switch (statue) {
      case 200:
        return result;
        break;
      case 401:
        throw NeedLogin();
        break;
      case 403:
        throw NeedAuth(result.toString(), data: result);
        break;
      default:
        throw HiNetError(statue, result.toString(), data: result);
        break;
    }
  }

  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    ///使用Dio发送请求
    // HiNetAdapter adapter = DioAdapter();
    HiNetAdapter adapter = MockAdapter();
    return adapter.send(request);
  }

  void printLog(log) {
    print("hi_net:" + log.toString());
  }
}
